/**
 * @description www-index
 *
 * @author xiaomi
 */

const readFrontRoutes = require('../../utils/read-front-routes');
const pathToRegexp = require('path-to-regexp');
const logger = require('../../services/logger');
const querystring = require('querystring');
const getClientByUA = require('../../utils/get-client-by-ua');
const getManifest = require('../../services/get-manifest');

const appName = 'www';
const PATHS = require('../../../webpack.paths')({
    appName: appName
});

module.exports = function(app) {
    const env = process.env;
    const router = app.router;
    const IS_PROD = env.NODE_ENV === 'production';
    // const Manifest = app.models.Manifest;
    const Offline = app.models.Offline;
    const cdnBaseUrl = PATHS.PUBLIC;

    const homeMW = function *() {
        const user = this.req.user || null;
        const pathNames = this.path.split('/').slice(1).map(name => {
            if(!name) {
                return 'index';
            }

            if(+name > 0) {
                return 'item';
            }

            return name;
        });

        const manifestsMap = yield getManifest();

        yield this.render('index', {
            env: env,
            path: this.path,
            pathNames: pathNames,
            user: user,

            cdnBaseUrl: cdnBaseUrl,
            manifestsMap: manifestsMap,
            getHashUrl(uri) {
                return IS_PROD && manifestsMap[uri] || uri;
            },
            getCdnUrl(uri) {
                uri = this.getHashUrl(uri);

                return cdnBaseUrl + uri;
            }
        });
    };

    // Front routes
    // router.get('/', homeMW);
    // router.get('/detail/:id', homeMW);
    // router.get('/detail', homeMW);
    // router.get('/posts/:id', homeMW);
    // router.get('/introduction', homeMW);
    // router.get('/private-protocol', homeMW);
    // router.get('/user-protocol', homeMW);
    // router.get('/user-vip-protocol', homeMW);

    readFrontRoutes('views/www/routes.js')
    .map(item => {
        const redirect = item.redirect || '';
        const path = item.path || '';

        if(!path || path === '*') {
            return;
        }

        if(redirect) {
            const toPath = pathToRegexp.compile(redirect);
            const statusCode = +item.statusCode || 302;

            router.get(path, function *() {
                const urlData = this._parsedUrl || {};
                const url = toPath(this.params) + (urlData.search || '');

                this.status = statusCode;
                this.redirect(url);
            });

            return;
        }

        router.get(path, homeMW);
    })
    .catch(err => {
        logger.error(err);

        process.exit(1);
    });

    // @TODO: 支持 H5 离线页回退
    router.get('/h5/*', function *() {
        const path = this.path;

        // if(/^\/h5\/(https?:\/\/.+)/i.test(path)) {
        //     this.redirect(RegExp.$1);

        //     return;
        // }
        const client = getClientByUA(this.get('User-Agent'));
        // H5 配置
        const offline = yield Offline.query(qb => {

            qb.whereNot('deleted', Offline.DELETED);

            qb.where('status', Offline.ONLINE);
            qb.where('clients', '&', client.id);

            qb.orderBy('id', 'desc');
        })
        .fetch();

        if(/^\/h5\/?/i.test(path)) {
            const query = querystring.stringify(this.query);
            const prefix = process.env.API_HOST.indexOf('.dev') > -1 ? 'development' : 'production';
            const distUrl = path.replace(/^\/h5/g, `/h5/${prefix}/${offline.get('id')}`);
            this.redirect(`http://${process.env.QINIU_HOST}${distUrl}?${query}`);
            return;
        }

        this.body = `URL: ${path}`;
    });
};
